""" 

    News.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a list of Ids and returns a list of the 10 most recent
    news stories from the legislator's RSS feed.
    
    A user must be logged into facebook in order to receive "like/dislike" information from this service

    Accepts two parameters:
        ids (required) - comma delimited list of Bioguide Ids
        offset (optional) - used for paging to get records 11-20, 21-30, etc.
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import wsgiref.handlers
import const
import facebook

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
        
from utils import fbUtil, SunlightUtil, memcacheUtil, textUtil

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "news":[]}

        theIds = self.request.get('ids', default_value=None)

        if theIds is not None:
            news = {}
            newsCount = 10
            newsOffset = int(self.request.get('offset', default_value=0))
            
            legislatorIds = theIds.split(",")
            sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
            memcache = memcacheUtil()
            
            # get the info about extended permissions
            try:
                self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
                if self.facebookapi is None:
                    jsonOutput["loggedin"] = False
                else:
                    jsonOutput["loggedin"] = True
                    jsonOutput["linkPermission"] = self.facebookapi.users.hasAppPermission("share_item")                
            except facebook.FacebookError, e:
                jsonOutput["loggedin"] = False
                
            for legislatorId in legislatorIds:
                legislator = sunlight.apicall("legislators.get", {"bioguide_id": legislatorId})
                if legislator is not None:               
                    legislator_news = memcache.getJSONFromRSSCache(legislator["legislator"]["official_rss"])
                    if legislator_news is not None:
                        for newsItem in legislator_news:
                            newsItem["name"] = const.FRIENDLY_NAME[legislatorId]
                            newsItem["id"] = legislatorId
                            news[newsItem["pubDate"]] = newsItem
                
            keys = news.keys()
            keys.sort(reverse=True)
            if keys is not None:
                  
                if len(keys) < (newsCount+newsOffset):
                    newsCount = len(keys) - newsOffset
                
                textutil = textUtil()
                for newsIndex in range(newsCount):
                    if (newsIndex + newsOffset) < len(keys):
                        jsonOutput["news"].append(news[keys[newsIndex]])
                                                 

        else:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = "missing IDs"
                          
        self.response.out.write(simplejson.dumps(jsonOutput))
        
        
def main():
    application = webapp.WSGIApplication([('/fb/news', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
